package org.ala.tcp_feign_common.handler;

import java.util.HashMap;
import java.util.Map;

import org.ala.tcp_feign_common.enums.TcpFeignMessageTypeEnums;
import org.ala.tcp_feign_common.logs.LoggerFactory;
import org.ala.tcp_feign_common.msg.AbstractByteMessage;
import org.slf4j.Logger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 读到消息处理器
 *
 * @author 骆毅(ala)
 * @date 2024年4月19日
 */
public class ByteMessageReadHandler extends ChannelInboundHandlerAdapter {
	
	
	static Logger log = LoggerFactory.getLogger("tcp-feign", "handler");

	
	/**
	 * 消息处理器
	 */
	@SuppressWarnings("rawtypes")
	protected Map<TcpFeignMessageTypeEnums, IByteMessageAction> actionMapper;
	/**
	 * 初始化
	 */
	public void init() {
		actionMapper = new HashMap<>();
	}
	/**
	 * 追加action
	 */
	@SuppressWarnings("rawtypes")
	public void append(IByteMessageAction action) {
		if (actionMapper == null) {
			synchronized (ByteMessageReadHandler.class) {
				if (actionMapper == null) {
					actionMapper = new HashMap<>();
				}
			}
		}
		actionMapper.put(action.type(), action);
	}
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		//	根据消息类型执行不同的action
		AbstractByteMessage byteMsg = (AbstractByteMessage) msg;
		
//		log.info("[ByteMessageReadHandler channelRead] 消息handler msg.type:" + byteMsg.type());
		
		IByteMessageAction action = actionMapper.get(byteMsg.type());
		
		//	处理执行动作
		if (action != null) {
			action.action(ctx, byteMsg);
		}
		
		//	到此为止，不再往下传播
//		super.channelRead(ctx, msg);
	}

}
